<template>
	<view class="">
		<text>同步缓存如果需要判断是否设置成功可以捕获异常，通常这种情况需要用异步</text>
		<br />
		<view class="">
			<text>同步缓存设置</text>
			<br />
			<text>已设置缓存：{{name}}</text>
			<button type="default" @click="setssync">设置缓存</button>
			<button type="default" @click="getssync">取出缓存</button>
			<button type="default" @click="remosync">删除缓存</button>
			<button type="warn" @click="remoallsync">删除所有缓存</button>
		</view>
	</view>
	<view class="">==========</view>
	<view class="">
		<text>异步缓存设置</text>
		<view class="">
			<text>已设置缓存：{{name}}</text>
			<button type="default" @click="sets">设置缓存</button>
			<button type="default" @click="gets">取出缓存</button>
			<button type="default" @click="remo">删除缓存</button>
			<button type="warn" @click="remoall">删除所有缓存</button>
		</view>
	</view>
</template>

<script setup>
	
	const name = ref('null')
	// 同步缓存如果需要判断是否设置成功可以捕获异常，通常这种情况需要用异步
	// try {
	//   uni.setStorageSync('key', 'value');
	//   console.log('缓存设置成功');
	// } catch (e) {
	//   console.error('缓存设置失败:', e);
	// }

	console.log(name);
	
	function setssync(){
		uni.setStorageSync('name','谨念')
		name.value = '已设置名字';
	}
	function getssync(){
		name.value = '以取出名字'+uni.getStorageSync('name')
	}
	function remosync(){
		uni.removeStorageSync('name')
		name.value = '已删除名字';
	}
	function remoallsync(){
		uni.clearStorageSync()
		name.value = '已全部删除';
	}
	
	
	function sets(){
		uni.setStorage({
			key:'name',
			data:'谨念',
			success:function(e){
				name.value = '已设置名字';
				uni.showToast({
					title:"已设置名字"
				})
			},
			fail:function(e){
				console.log(e)
			},
			complete:function(e){
				console.log('complete')
			}
		})
	}
	function gets(){
		
		uni.getStorage({
			key:'name',
			success:function(e){
				console.log(e)
				name.value = '以取出名字：'+e.data;
				uni.showToast({
					title:"以取出名字"
				})
			},
			fail:function(e){
				console.log(e)
				uni.showToast({
					title:e.errMsg
				})
			},
			complete:function(e){
				console.log('complete')
			}
		})
	}
	function remo(){
		uni.removeStorage({
			key:'name',
			success:function(e){
				console.log(e)
				name.value = '已删除名字';
				uni.showToast({
					title:'ok'
				})
			},
			fail:function(e){
				console.log(e)
				uni.showToast({
					title:e.errMsg
				})
			},
			complete:function(e){
				console.log('complete')
			}
		})
	}
	function remoall(){
		uni.clearStorage()
		uni.showToast({
			title:'ok'
		})
		name.value = '已全部删除';
	}
	
</script>

<style lang="scss" scoped>

</style>
